package middleware

import (
	"context"
	"everyone/C/api_C/internal/types"
	"everyone/C/api_C/pkg"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := &types.Response{
				Code: 1001,
				Msg:  "中间鉴为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		userId, err := pkg.ParseJwtToken(token)
		if err != nil {
			resp := &types.Response{
				Code: 1002,
				Msg:  "中间鉴为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		cxt := context.WithValue(context.Background(), "userId", userId)
		// Passthrough to next handler if need
		next(w, r.WithContext(cxt))
	}
}
